import os
import numpy as np
import tensorflow as tf
import classification.dataPreparation.load_data as load_data
import classification.cnn.cnn as cnn
from classification.config.Params import Params


params = Params()
# train, train_label = input_data.get_files(train_dir)
train, train_label, val, val_label = load_data.get_files(params.samples_path)
# 训练数据及标签
train_batch, train_label_batch = load_data.get_batch(train, train_label, params.shape, params.batch_size, params.capacity)
# 测试数据及标签
val_batch, val_label_batch = load_data.get_batch(val, val_label, params.shape, params.batch_size, params.capacity)

# 训练操作定义
train_logits = cnn.inference(train_batch, params.batch_size, params.n_classes)
train_loss = cnn.losses(train_logits, train_label_batch)
train_op = cnn.trainning(train_loss, params.learning_rate)
train_acc = cnn.evaluation(train_logits, train_label_batch)

# 测试操作定义
test_logits = cnn.inference(val_batch, params.batch_size, params.n_classes)
test_loss = cnn.losses(test_logits, val_label_batch)
test_acc = cnn.evaluation(test_logits, val_label_batch)

# 这个是log汇总记录
summary_op = tf.summary.merge_all()

# 产生一个会话
sess = tf.Session()
# 产生一个writer来写log文件
train_writer = tf.summary.FileWriter(params.logs_train_path, sess.graph)
# val_writer = tf.summary.FileWriter(logs_test_dir, sess.graph)
# 产生一个saver来存储训练好的模型
saver = tf.train.Saver()
# 所有节点初始化
sess.run(tf.global_variables_initializer())
# 队列监控
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

# 进行batch的训练
try:
    # 执行MAX_STEP步的训练，一步一个batch
    for step in np.arange(params.max_step):
        if coord.should_stop():
            break
            # 启动以下操作节点，有个疑问，为什么train_logits在这里没有开启？
        _, tra_loss, tra_acc = sess.run([train_op, train_loss, train_acc])

        # 每隔50步打印一次当前的loss以及acc，同时记录log，写入writer
        if step % 1 == 0:
            print('Step %d, train loss = %.2f, train accuracy = %.2f%%' % (step, tra_loss, tra_acc * 100.0))
            summary_str = sess.run(summary_op)
            train_writer.add_summary(summary_str, step)
            # 每隔100步，保存一次训练好的模型
        if (step + 1) == params.max_step:
            checkpoint_path = os.path.join(params.logs_train_path, 'model.ckpt')
            saver.save(sess, checkpoint_path, global_step=step)

except tf.errors.OutOfRangeError:
    print('Done training -- epoch limit reached')

finally:
    coord.request_stop()
